/* pages/home/home.ts */
interface OutRecord {
    name: string;
    quantity: number;
    unitPrice: number;
    totalPrice: number;
    date: string;
    customerName: string; // 新增字段
}

Page({
    data: {
        month: new Date().getMonth() + 1,
        year: new Date().getFullYear(),
        outRecords: [] as OutRecord[], // 存储出库记录
        totalAmount: 0, // 当月出库总金额
        totalCount: 0, // 当月出库总次数
        isYearly: false, // 是否按年查询
        yearRange: Array.from({ length: 10 }, (_, i) => new Date().getFullYear() - i), // 过去10年
        monthRange: Array.from({ length: 12 }, (_, i) => (i + 1).toString()) // 1到12月
    },

    onLoad() {
        this.loadOutRecords();
    },

    onShow() {
        this.loadOutRecords(); // 页面显示时重新加载数据
    },

    loadOutRecords() {
        const { month, year, isYearly } = this.data;
        const records: OutRecord[] = wx.getStorageSync('outRecords') || [];
        const filteredRecords = records.filter(record => {
            const recordDate = new Date(record.date);
            return isYearly
                ? recordDate.getFullYear() === Number(year)
                : recordDate.getMonth() + 1 === Number(month) && recordDate.getFullYear() === Number(year);
        });

        const totalAmount = filteredRecords.reduce((sum, record) => sum + record.totalPrice, 0);
        const totalCount = filteredRecords.length;

        this.setData({
            outRecords: filteredRecords,
            totalAmount,
            totalCount
        });
    },

    onMonthChange(e: WechatMiniprogram.PickerChange) {
        const value = e.detail.value as string;
        const [year, month] = value.split('-').map(Number);
        this.setData({
            year,
            month,
            isYearly: false
        }, () => {
            this.loadOutRecords();
        });
    },

    onYearChange(e: WechatMiniprogram.PickerChange) {
        const value = e.detail.value as unknown as number[];
        const yearIndex = value[0];
        const year = this.data.yearRange[yearIndex];
        this.setData({
            year,
            isYearly: true
        }, () => {
            this.loadOutRecords();
        });
    },

    onAddRecord() {
        wx.navigateTo({
            url: '/pages/addRecord/addRecord'
        });
    },

    showAddRecord() {
        wx.navigateTo({
            url: '/pages/addRecord/addRecord'
        });
    },

    goToHome() {
        wx.navigateTo({
            url: '/pages/home/home'
        });
    },

    goToCustomer() {
        wx.navigateTo({
            url: '/pages/customer/customer'
        });
    },

    goToStatistics() {
        wx.navigateTo({
            url: '/pages/chart/chart' 
        });
    },

    goToProfile() {
        wx.navigateTo({
            url: '/pages/profile/profile'
        });
    }
});
